home *** CD-ROM | disk | FTP | other *** search
- Path: news.netzone.com!usenet
- From: steveng@netzone.com (Steven Gavette)
- Newsgroups: comp.lang.c
- Subject: Re: Pointers to structures
- Date: 3 Jan 1996 20:13:48 GMT
- Organization: NetZone, Inc. (602) 991-4NET
- Message-ID: <4ceo1s$fhe@news1.netzone.com>
- References: <4cc9r4$m26@armitage.cyberspace.com> <DKLDnH.96B@eskimo.com>
- NNTP-Posting-Host: phx-ip-49.netzone.com
- X-Newsreader: WinVN 0.99.7
-
- In article <DKLDnH.96B@eskimo.com>, mag@eskimo.com says...
- >
- >In article <4cc9r4$m26@armitage.cyberspace.com> (2 Jan 1996 21:59:00 GMT),
- icaru
- >s@loomis
- >says :
- >>
- >>I'm having trouble using a pointer to a struct. The idea is to have a
- >>struct get filled by a function, which gets the address and everything
- >>via function(struct type*). Very straightforward. However, if I try to
- >>CHANGE anything in the struct, it just goes back when the function is
- >>over. So, let's pretend this imaginary structure is what I'm using:
- >>
- >>struct st1 {
- >> char *name;
- >> int yadda;
- >>};
- >>
- >>And the function is:
- >>
- >>fn1(struct st1 *st)
- >>{
- >> st = (struct st1*)malloc(sizeof(struct st1*));
- >> st->name = (char*)malloc(16);
- >> strcpy(st->name,"Test");
- >> st->yadda = 100;
- >>}
- >>
- >>At the last line of code in fn1, all the values are correct; st->name is
- >>"Test" and st->yadda is 100. As soon as it exits, however, st->name
- >>points to NULL and st->yadda is zero. The allocation of the structure in
- >>the first line of fn1 doesn't seem to matter; both ways, I get NULL
- >>pointers coming out of my ears.
- >>
-
- I think your problem is that you're not returning the new address to the
- calling function. If you want to create the structure in your "fill"
- function, there's no need to pass it a pointer. But you DO need to return it.
- If you are in fact passing the "fill" function a pointer to an existing
- structure, there's no need to allocate memory for it. You need to choose
- which way you're going to do it.
-
- Steve
-
-